<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="80px">
        <el-form-item label="计划年月">
          <el-date-picker
            v-model="searchParam.yearMonthPlan"
            type="month"
            placeholder="请输入年月"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择产品"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            展示
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!--<el-button type="primary" @click="validIsSearched(6)">
          新增物料
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="validIsSearched(4)"
        >
          批量确认
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="validIsSearched(5)"
        >
          批量允许发货
        </el-button>
        <el-button type="primary" @click="validIsSearched(3)">
          导入计划</el-button
        >
        <el-button type="primary" class="ml-3" @click="downLoad">
          <template #icon><i-ep-download /></template>导出</el-button
        >-->
        <!--<el-button
          type="success"
          :disabled="totalMultipleSelection.length === 0"
          @click="calculationPlan()"
        >智能计算</el-button
        >-->
        <el-button type="primary" @click="open()" v-if="!isOpen"
          >展开</el-button
        >
        <el-button type="primary" @click="close()" v-if="isOpen"
          >收起</el-button
        >
        <el-button
          type="success"
          @click="parameterSetting()"
          :disabled="!searchParam.yearMonthPlan || intervalDayList.length === 0"
          >参数设置</el-button
        >
        <el-button
          type="warning"
          @click="calculationPlan()"
          :disabled="!searchParam.yearMonthPlan || tableData.length === 0"
          >智能排产</el-button
        >
      </template>

      <!-- 导入计划 -->
      <ImportExcel ref="weekImportRef" />

      <!-- 合计行的id定义为-999，当表格返回-999时，没有点击事件，展示合计行内容 -->

      <!-- objectSpanMethod方法，objectSpanMethod(param, 3, 7)
      参数3 代表三行合并
      参数13 代表从第13 + 1 列开始取消合并 -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :span-method="(param) => objectSpanMethod(param, 3, defaluleRow)"
        :header-cell-style="{ textAlign: 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
        show-summary
        :summary-method="footerMethod"
      >
        <!--<el-table-column
          type="selection"
          width="55"
          align="center"
          fixed
          :selectable="selectableStatus"
        />-->
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index, row }">
            <span v-if="row.id !== '-999'">{{ $index / 3 + 1 }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="产品名称"
          prop="materialCode"
          width="200"
          show-overflow-tooltip
          fixed
          align="left"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span v-if="row.id != -999">
              <!--class="cursor-pointer decoration-underline p-0! can_edit_cell"-->
              <!--@click="planMaterial(row)"-->
              {{ row.materialName }}
            </span>
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="砂芯编号"
          prop="sandCoreNumber"
          min-width="85"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="总计套数"
          prop="allTotal"
          min-width="85"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="件/M"
          prop="pm"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="M/S"
          prop="ms"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="班制"
          prop="shiftSet"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          label="班产数量"
          prop="tactYield"
          min-width="85"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="期初库存/件"
          prop="openingInventory"
          min-width="100"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              v-if="row.id != -999"
              @click="openEditPrompt(row)"
              >{{ row.openingInventory }}</span
            >
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="冷芯/热芯"
          prop="coreState"
          min-width="90"
          align="center"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="设备型号"
          prop="equipModel"
          sortable
          min-width="110"
          align="left"
          class-name="padding012"
        />
        <!-- <el-table-column
          v-if="isOpen"
          label="设备"
          prop="equipName"
          min-width="100"
          align="center"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              v-if="row.id != -999"
              @click="openEditEquip(row)"
              >{{ row.equipName ? row.equipName : "未设置" }}</span
            >
            <span class="text-[13px]" v-else> </span>
          </template>
        </el-table-column> -->
        <el-table-column
          v-if="isOpen"
          label="砂型号"
          prop="sandModel"
          min-width="200"
          align="left"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="需求人数"
          prop="demandPeople"
          min-width="85"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span class="text-[13px]" v-if="row.id != -999">{{
              row.demandPeople
            }}</span>
            <span style="padding: 0 0" v-else>需求人数</span>
          </template>
        </el-table-column>
        <el-table-column label="大项" width="90" align="center">
          <template #default="{ row, $index }">
            <div v-if="row.id != '-999'">
              <span class="text-[13px]" v-if="($index + 1) % 3 == 1"
                >要货数量</span
              >
              <span class="text-[13px]" v-if="($index + 1) % 3 == 2"
                >计划套数</span
              >
              <span class="text-[13px]" v-if="($index + 1) % 3 == 0"
                >完成数量</span
              >
            </div>
            <div v-else></div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(dayItem, dayIndex) in intervalDayList"
          :key="dayIndex"
          :label="`${dayItem.date}\n${dayItem.week}`"
          :label-class-name="
            dayItem.week == 0 || dayItem.week == 6 ? 'bg-free' : ''
          "
          min-width="80"
          align="right"
        >
          <template #header="{ column }">
            <span @click="oneDay(dayItem)" class="cursor-pointer cellNumber">{{
              column.label
            }}</span>
          </template>
          <template
            #default="{
              row,
              $index,
              detailIndex = row.details.findIndex(
                (item) => getMonthAndDay(item.planDate) === dayItem.date
              ),
              listPlanActualIndex = row.listPlanActual.findIndex(
                (item) => getMonthAndDay(item.requireDate) === dayItem.date
              ),
            }"
          >
            <div
              :style="{
                backgroundColor:
                  inConsistentOne(row, $index, detailIndex) == ''
                    ? ''
                    : inConsistentOne(row, $index, detailIndex),
              }"
            >
              <!-- 要货数量 -->
              <div v-if="($index + 1) % 3 == 1" style="height: 25px">
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                  @click="updateColour(row, detailIndex)"
                >
                  {{ row.details[detailIndex]?.quantity || "" }}
                </span>
                <span v-else>
                  {{ getPeopleSum(row, detailIndex, listPlanActualIndex) }}
                  <!--                  {{ row.details[detailIndex]?.quantity || "" }}-->
                </span>
              </div>
              <!-- 计划套数 -->
              <div
                v-if="($index + 1) % 3 == 2"
                @click="
                  clickJudge(
                    row,
                    intervalDayList[dayIndex],
                    listPlanActualIndex
                  )
                "
                style="height: 25px"
                class="cursor-pointer cellNumber"
              >
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                >
                  {{
                    row.listPlanActual[listPlanActualIndex]?.planQuantity || ""
                  }}
                </span>
                <!--<span v-else>
                  {{ row.listPlanActual[dayIndex]?.planQuantity }}
                </span>-->
              </div>
              <!-- 完成数量 -->
              <div v-if="($index + 1) % 3 == 0" style="height: 25px">
                <span v-if="row.id !== '-999'">
                  <!--class="cursor-pointer cellNumber"
                  @click="openFeedbackInfo(row.id,'完成信息')"-->
                  {{
                    row.listPlanActual[listPlanActualIndex]?.finishQuantity ||
                    ""
                  }}
                </span>
                <!--<span v-else>
                  {{ row.listPlanActual[dayIndex]?.finishQuantity }}
                </span>-->
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增物料弹窗 -->
    <plan-purchase-demand-add-dialog
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      @reset-table="getTableList(0)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 产品详情 -->
    <plan-material-dialog
      :visible="addNewDialog.visible"
      :title="addNewDialog.title"
      :materialId="addNewDialog.materialId"
      :data="addNewDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 预留 -->
    <plan-require-goods-add-dialog
      :visible="addGoodsDialog.visible"
      :title="addGoodsDialog.title"
      :id="addGoodsDialog.id"
      :cellId="addGoodsDialog.cellId"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      :data="addGoodsDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="addGoodsDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 计划模数修改 -->
    <plan-core-info-dialog
      :visible="feedbackDialog.visible"
      :title="feedbackDialog.title"
      :cellId="feedbackDialog.cellId"
      :demandStatus="feedbackDialog.demandStatus"
      :endDate="feedbackDialog.endDate"
      :begirate="feedbackDialog.beginDate"
      :data="feedbackDialog.data"
      @reset-table="getTableList(0)"
      :is-readonly="feedbackDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />

    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
    <!--参数设置-->
    <core-reckon-parameter-setting
      :visible="addDialogReckon.visible"
      :title="addDialogReckon.title"
      :data="addDialogReckon.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialogReckon.readvisible"
      @change-visible="changeVisibleReckon"
    />
  </div>
</template>

<script setup lang="ts">
import {
  resolveSearchData,
  objectSpanMethod,
  getDaysByMonth,
  selectableStatus,
  inConsistentOne,
} from "./utilejs/index";
import { filterOrder, promptValidateNumber } from "@/utils/commonHooks";
import dayjs from "dayjs";
import request from "@/utils/request";
import { useDownload } from "@/utils/useTable";
import Big from "big.js";
import { ElMessageBox, ElSelect, ElOption } from "element-plus";

defineOptions({
  name: "MESMESCOREMONTHPLAN",
  inheritAttrs: false,
});

// 初始化搜索参数数据
const searchParam = reactive<any>({
  materialId: "",
  materialCode: "",
  yearMonthPlan: getCurrentMonth(),
});

// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<any>({
  materialId: "",
  materialCode: "",
  yearMonthPlan: getCurrentMonth(),
});

// 搜索时间变化后处理函数
const intervalDayList = ref<any[]>([]);

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
// 表格选择
const totalMultipleSelection: any = ref([]);
function handleSelectionChange(selection: any[]) {
  // ids.value = selection.map((item: TableResultObject) => item.id);
  totalMultipleSelection.value = selection;
}

// 开始展示逻辑处理
const loading = ref(false);
const tableData = ref([]);
// 点击展示之前
function beforeGetTableList() {
  if (!searchParam.yearMonthPlan) {
    ElMessage.error("请选择计划月");
    return;
  }
  getTableList(1);
}
const isOpen = ref(true);
const defaluleRow = ref(13);
function open() {
  isOpen.value = true;
  defaluleRow.value = 13;
}
function close() {
  isOpen.value = false;
  defaluleRow.value = 5;
}
//原始数据
const selectDataStat = ref([]);
// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/mes/mescoremonthplan/queryByList",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {
    // //以下为模拟数据，待真实接口后，可删除
    //
    // // 储存被搜索条件
    // Object.assign(searchedParam, {
    //   ...toRaw(searchParam),
    // });
    // // 时间处理
    // intervalDayList.value = getDaysByMonth(searchParam.yearMonthPlan);
    // // 数据处理
    // tableData.value = resolveSearchData(mockTableList);
    //
    // loading.value = false;
  });
  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  startData.value = data;
  // 时间处理
  intervalDayList.value = getDaysByMonth(searchParam.yearMonthPlan);
  // 数据处理
  tableData.value = resolveSearchData(data);
  selectDataStat.value = data;
  loading.value = false;
}

// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

// 新增物料弹窗及操作逻辑
const addDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  addGoodsDialog.visible = value;
  feedbackDialog.visible = value;
  addNewDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    addGoodsDialog.data = {};
    addGoodsDialog.cellId = "";
    addGoodsDialog.id = "";
    feedbackDialog.data = {};
    feedbackDialog.cellId = "";
    addNewDialog.data = {};
    detailData = {};
  }
}

// 新增要货弹窗及操作逻辑
const addGoodsDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  id: "",
});
let detailData = reactive({
  id: "",
  // organizationId: "",
  // organizationCode: "",
  // organizationName: "",
  // plantId: "",
  // plantCode: "",
  // plantName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  planId: "",
  planQuantity: "",
  // finishQuantity: "",
  // status: "",
  // version: "",
  // remarks: "",
  // createdUserName: "",
  // createdTime: "",
  // lastUpdateUserName: "",
  // lastUpdateTime: "",
  // deleted: "",
  // createdUserId: "",
  // lastUpdateUserId: "",
  requireDate: "",
  tactYield: "",
});
const updateColour = (row?: any, detailIndex: number) => {
  if (row.details[detailIndex]?.status === 1) {
    ElMessageBox.confirm("是否确认?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const one = row.details[detailIndex];
        one.status = 2;
        const res: any = await request({
          url: `/mes/mescoremonthplanrequire/save`,
          method: "post",
          data: one,
        });
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "确认成功",
          });
          getTableList(1);
        }
      })
      .catch(() => {});
  }
};
//单击双击事件
const isOne = ref(false); // 判断是否有第一次点击
const isTwo = ref(false); // 判断是否有第二次点击
const delayTime = ref(300); // 单击事件的延迟时间，同时是双击的判断阈值
const clickJudge = (row, day, listPlanActualIndex) => {
  console.log("isOne.value", isOne.value);
  console.log("isTwo.value", isTwo.value);
  if (!isOne.value) {
    // 如果是第一次点击
    isTwo.value = false; // 重置双击判断函数
    isOne.value = true;
    setTimeout(() => {
      // 如果延迟函数期间执行了第二次点击 则不执行单击事件
      if (!isTwo.value) {
        OneClick(row, day, listPlanActualIndex);
        isOne.value = false;
      }
    }, delayTime.value);
  } else {
    //  如果已经有第一次点击了 接下来便是第二次点击
    isTwo.value = true;
    TwoClick(row, day, listPlanActualIndex);
    // 双击执行完之后 需要重置判断属性
    isOne.value = false; // 重置单击判断函数
  }
};
const OneClick = (row, day, listPlanActualIndex) => {
  openFeedbackInfo(row.id, "计划信息", row, day, listPlanActualIndex);
  // 单击事件代码
  console.log("我被单击了");
};
const TwoClick = (row, day, listPlanActualIndex) => {
  openFeedbackInfoTwo(row, day, listPlanActualIndex);
  // 双击事件代码
  console.log("我被双击了");
};
// 反馈信息确认弹窗及操作逻辑
const feedbackDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  demandStatus: null,
});
const openFeedbackInfo = (
  cellId = "",
  title = "",
  row: any,
  day,
  listPlanActualIndex: number
) => {
  console.log("day", day.date);
  let flag = true;
  let element = row.listPlanActual[listPlanActualIndex];
  if (element != null) {
    detailData = element;
    flag = false;
  }
  detailData.materialId = row.materialId;
  detailData.materialCode = row.materialCode;
  detailData.materialName = row.materialName;
  detailData.requireDate = row.yearMonthPlan + "-" + day.date.slice(3, 5);
  detailData.planId = row.id;
  detailData.plantId = row.plantId;
  detailData.plantCode = row.plantCode;
  detailData.plantName = row.plantName;
  detailData.tactYield = row.tactYield;
  if (
    new Date(mesdayplan()) >
    new Date(row.yearMonthPlan + "-" + day.date.slice(3, 5))
  ) {
    ElMessage.error("只能修改当天和当天以后数据！");
    return;
  }
  if (element?.status === 1) {
    ElMessage.error("日计划已生成，不可编辑！");
    return;
  }
  if (flag) {
    detailData.id = "";
    detailData.planQuantity = 0;
  }
  const object = {
    visible: true,
    title: title,
    beginDate: dayjs(searchedParam.yearMonthPlan)
      .startOf("month")
      .format("YYYY-MM-DD"),
    endDate: dayjs(searchedParam.yearMonthPlan)
      .endOf("month")
      .format("YYYY-MM-DD"),
    cellId: cellId,
    data: detailData,
  };
  Object.assign(feedbackDialog, { ...object });
};

async function openFeedbackInfoTwo(row: any, day, listPlanActualIndex) {
  loading.value = true;
  console.log("day", day.date);
  let element = row.listPlanActual[listPlanActualIndex];
  if (element != null) {
    detailData = deepClone(element);
  }
  detailData.materialId = row.materialId;
  detailData.materialCode = row.materialCode;
  detailData.materialName = row.materialName;
  detailData.requireDate = row.yearMonthPlan + "-" + day.date.slice(3, 5);
  detailData.planId = row.id;
  detailData.plantId = row.plantId;
  detailData.plantCode = row.plantCode;
  detailData.plantName = row.plantName;
  if (
    new Date(mesdayplan()) >
    new Date(row.yearMonthPlan + "-" + day.date.slice(3, 5))
  ) {
    ElMessage.error("只能修改当天和当天以后数据！");
    loading.value = false;
    return;
  }
  if (element?.status === 1) {
    ElMessage.error("日计划已生成，不可编辑！");
    loading.value = false;
    return;
  }
  if (detailData.planQuantity > 0) {
    loading.value = false;
    return;
  }
  detailData.planQuantity = row.tactYield;
  await request({
    url: "/mes/mescoremonthplanactual/save",
    method: "post",
    data: detailData,
  }).finally(() => {});
  ElMessage.success(`成功`);
  await getTableList(1);
  detailData = {};
}
//深拷贝
function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}
// 获取当前日期yyyymmdd
function mesdayplan() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  const day = ("0" + now.getDate()).slice(-2);
  return year + "-" + month + "-" + day;
}
// 操作前校验是否搜索过
function validIsSearched(type: number) {
  if (!searchedParam.yearMonthPlan) {
    ElMessage.error("请先选择计划月后，再进行操作");
    return;
  } else {
    // 导入计划
    if (type === 3) {
      weekBatchImport();
    }

    // 批量确认
    if (type === 4) {
      confirmBatch();
    }

    // 批量允许发货
    if (type === 5) {
      sendAbleBatch();
    }

    // 新增物料(新版)
    if (type === 6) {
      openAddMaterialNew();
    }
  }
}

// 导入计划
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/srm/srmmaterialdemand/upload", formdata, config)
    .then((res: any) => {
      weekImportRef.value.resCode = res.code;
      if (res.code === 300) {
        errorDataList.value = res.data;
        uploadErrorRef.value.errorBox = true;
      }
    })
    .catch((e) => {
      weekImportRef.value.resCode = 500;
    });
}
const weekBatchImport = () => {
  let params = {
    title: "导入计划",
    tempApi: "", //模板下载
    importApi: weekImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {
      yearMonthPlan: searchedParam.yearMonthPlan,
    },
  };
  weekImportRef.value.acceptParams(params);
};

// 导出
const downLoad = () => {
  if (!searchedParam.yearMonthPlan) {
    ElMessage.error("请先选择计划月后，再进行操作");
    return;
  } else {
    useDownload(
      "/srm/srmmaterialdemand/export",
      "采购需求",
      searchParam,
      true,
      ".xls"
    );
  }
};

function confirmBatch() {
  ElMessageBox.confirm("请确认，是否继续批量确认操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/srm/srmdemandschedule/confirmBatch",
          method: "post",
          data: {
            yearMonthPlan: searchedParam.yearMonthPlan,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量确认成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}

function sendAbleBatch() {
  ElMessageBox.confirm("请确认，是否继续批量允许发货操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/srm/srmdemandschedule/sendAbleBatch",
          method: "post",
          data: {
            yearMonthPlan: searchedParam.yearMonthPlan,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量允许发货成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}
// 新增物料（新版）弹窗及操作逻辑
const addNewDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  materialId: "",
});
const planMaterial = (row) => {
  const object = {
    visible: true,
    title: "产品详情",
    materialId: row.materialId,
  };
  Object.assign(addNewDialog, { ...object });
};

const openEditPrompt = (row: any) => {
  ElMessageBox.prompt("期初库存（件）", row.materialName, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    customClass: "prompt_custom",
    closeOnClickModal: false,
    inputValue: row.openingInventory,
    inputValidator: (value: string) => promptValidateNumber(value),
  })
    .then(async ({ value }) => {
      row.openingInventory = value;
      const res = await request({
        url: "/mes/mescoremonthplan/save",
        method: "post",
        data: row,
      });
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: `修改成功`,
        });
        getTableList(1);
      }
    })
    .catch(() => {});
};
const selectedValue = ref("option1");

const openEditEquip = async (row: any) => {
  const equipId = row.equipId;
  const equipCode = row.equipCode;
  const equipName = row.equipName;

  //设备
  const equipList = ref([]);
  const { data } = await request({
    url: "/mdm/mdmequipinfo/getList",
    method: "post",
    data: { equipTypeName: row.equipModel },
  });
  equipList.value = data;
  // 根据 equipList 动态生成 selectOptions
  const selectOptions = () =>
    equipList.value.map((item) =>
      h(ElOption, {
        key: item.id, // 添加 key 提高性能
        label: item.equipName,
        value: item.id,
      })
    );

  const select = () =>
    h(
      ElSelect,
      {
        modelValue: row.equipId,
        placeholder: "请选择",
        "onUpdate:modelValue": (val) => {
          equipList.value.forEach((item) => {
            if (item.id === val) {
              row.equipCode = item.equipCode;
              row.equipName = item.equipName;
            }
          });
          row.equipId = val;
        },
      },
      selectOptions
    );

  ElMessageBox({
    title: "选择设备",
    message: select,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async ({ value }) => {
      const res = await request({
        url: "/mes/mescoremonthplan/save",
        method: "post",
        data: row,
      });
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: `修改成功`,
        });
        getTableList(1);
      }
    })
    .catch(() => {
      row.equipId = equipId;
      row.equipCode = equipCode;
      row.equipName = equipName;
    });
};
const getyearMonthPlan = async () => {
  const { data }: any = await request({
    url: "/mes/mesyearMonthPlan/queryByList",
    method: "post",
    data: data,
  });
  return data;
};
function getMonthAndDay(date: any) {
  let month = date?.slice(5, 7);
  let day = date?.slice(8, 10);
  return month + "/" + day;
}
//计算本月订单数量 = 要货数量合计
function sumThisMonthOrderQuantity(row: any) {
  var sum = 0;
  if (row.details.length > 0) {
    row.details.forEach((item: any) => {
      sum += item.quantity;
    });
  } else {
    sum = 0;
  }
  return sum;
}
//期末库存 = 总模数*每模多少个*（1-废品率）+期初库存-本月订单量
function getEndStock(row: any) {
  return (
    row.mfurnace * row.pm * ((100 - row.lastMonthScrapRate) * 0.01) +
    row.openingInventory -
    sumThisMonthOrderQuantity(row)
  );
}
//黑件生产量 = 计划总模数*每模多少个
function getBlackPieceQuantity(row: any) {
  var sum = 0;
  if (row.details.length > 0) {
    row.listPlanActual.forEach((item: any) => {
      sum += item.planQuantity;
    });
    sum = sum * row.pm;
  } else {
    sum = 0;
  }
  return row.mfurnace * row.pm;
}
const calculationPlan = async () => {
  ElMessageBox.confirm("确定对已选择数据进行智能计算吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mescoremonthplan/calculationPlan",
        method: "post",
        data: selectDataStat.value,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "计算完成",
        });
      }
      await getTableList(1);
    })
    .catch(() => {});
};
function getPeopleSum(
  row1: any,
  detailIndex: number,
  listPlanActualIndex: number
) {
  let planQuantitySum = 0;
  let tactYieldSum = 0;
  let demandPeopleSum = 0;
  let arr = [];
  //去除数据处理后id相同的数据
  arr = tableData.value.filter(
    (item, index, self) => self.findIndex((i) => i.id === item.id) === index
  );
  arr.forEach((row) => {
    if (row.id != "-999") {
      // row.listPlanActual.forEach((item, index) => {
      //   if (listPlanActualIndex == index) {
      //     console.log("index",index)
      //     console.log("item.planQuantity",item.planQuantity)
      //     planQuantitySum += item.planQuantity;
      //   }
      // });
      console.log(row.listPlanActual[listPlanActualIndex]);
      let listPlanActualElement = row.listPlanActual[listPlanActualIndex];
      if (listPlanActualElement != null) {
        planQuantitySum += listPlanActualElement.planQuantity;
      }
      tactYieldSum += row.tactYield;
      demandPeopleSum += row.demandPeople;
    }
  });
  // console.log("planQuantitySum",planQuantitySum)
  // console.log("tactYieldSum",tactYieldSum)
  // console.log("demandPeopleSum",demandPeopleSum)
  return planQuantitySum * (1 / tactYieldSum) * demandPeopleSum;
  // return demandPeopleSum +tactYieldSum ;
}
function footerMethod() {
  let tactYieldSum = 0;
  let demandPeopleSum = 0;
  let arr = [];
  //去除数据处理后id相同的数据
  arr = tableData.value.filter(
    (item, index, self) => self.findIndex((i) => i.id === item.id) === index
  );
  // 总合计算
  // let list = [];
  // arr.forEach((row) => {
  //   list.push(...row.listPlanActual);
  //   tactYieldSum += row.tactYield;
  //   demandPeopleSum += row.demandPeople;
  // });
  // // 初始化合计数组
  // let summary = [];
  // for (let i = 0; i < 11; i++) {
  //   summary.push("");
  // }
  // summary.push("操作人员需求数量："); //砂芯号列
  // summary.push(""); //需求人数列
  // summary.push(""); //大项列
  // intervalDayList.value.forEach((item) => {
  //   if (list.length > 0) {
  //     let daySum = 0;
  //     list.forEach((one: any) => {
  //       if (item.date == getMonthAndDay(one.requireDate)) {
  //         daySum += one.planQuantity;
  //       }
  //     });
  //     let s = daySum * (1 / tactYieldSum) * demandPeopleSum;
  //     if (s) {
  //       summary.push(s.toFixed(2));
  //     } else {
  //       summary.push("");
  //     }
  //   } else {
  //     summary.push("");
  //   }
  // });
  // 初始化合计数组 -- 每行单独算
  let summary = [];
  for (let i = 0; i < defaluleRow.value - 2; i++) {
    summary.push("");
  }
  summary.push("操作人员需求数量："); //砂芯号列
  summary.push(""); //需求人数列
  summary.push(""); //大项列
  intervalDayList.value.forEach((item) => {
    let rowSum = 0;
    arr.forEach((row) => {
      row.listPlanActual.forEach((one: any) => {
        if (item.date == getMonthAndDay(one.requireDate)) {
          // rowSum += one.planQuantity * (1 / row.tactYield) * row.demandPeople;
          rowSum += one.peopleNum;
        }
      });
    });
    if (rowSum) {
      summary.push(rowSum.toFixed(2));
    } else {
      summary.push("");
    }
  });
  nextTick(() => {
    if (dataTableRef.value.$el) {
      const current = dataTableRef.value.$el
        .querySelector(".el-table__footer-wrapper")
        .querySelector(".el-table__footer");
      const cell = current.rows[0].cells;
      cell[defaluleRow.value].style.display = "none";
      cell[defaluleRow.value - 2].colSpan = "2";
      cell[defaluleRow.value - 2].style.textAlign = "center";
      for (let i = 14; i < cell.length; i++) {
        cell[i].style.padding = "0 12px";
      }
    }
  });
  return summary;
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.materialId = data.id;
    searchParam.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  searchParam.materialId = "";
  searchParam.materialCode = "";
};
// 获取当前日期yyyy - mm
function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  return year + "-" + month;
}
const addDialogReckon = reactive<any>({
  visible: false,
  title: "",
  data: {},
  yearMonthPlan: "",
});
/** 打开制芯月计划计算表单弹窗 详情 */
async function parameterSetting() {
  addDialogReckon.title = "制芯月计划计算参数";
  addDialogReckon.data.shiftSetList = await getShiftSetList();
  addDialogReckon.data.intervalDayList = intervalDayList.value;
  await getReckonInfo(searchParam.yearMonthPlan);
}
// 查询详情
async function getReckonInfo(yearMonthPlan) {
  await request({
    url: `/mes/mescoremonthreckon/getList`,
    method: "post",
    data: { yearMonthPlan },
  }).then(async (res: any) => {
    if (res.data.length > 0) {
      Object.assign(addDialogReckon.data, res.data[0]);
      addDialogReckon.data.shiftSetIdData = res.data[0].details.map(
        (item: any) => ({
          shiftSystemId: item.shiftSystemId,
          shiftSystemName: item.shiftSystemName,
          planDate: item.planDate,
        })
      );
    } else {
      addDialogReckon.data.shiftSetIdData = await getProcessShiftSetIdList();
      addDialogReckon.data.yearMonthPlan = yearMonthPlan;
    }
    addDialogReckon.visible = true;
  });
}
function changeVisibleReckon(value: boolean) {
  addDialogReckon.visible = value;
  if (!value) {
    addDialogReckon.data = {};
  }
}
async function getShiftSetList() {
  let shiftSetList = [];
  await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: { plantCode: "GIANTECH", enabled: 1 },
  }).then((res) => {
    shiftSetList = res.data;
  });
  shiftSetMap.value = new Map(shiftSetList.map((item) => [item.id, item]));
  return shiftSetList;
}
const shiftSetMap: any = ref();
//默认班制值
async function getProcessShiftSetIdList() {
  const { data } = await request({
    url: `/mes/mesprocess/getList`,
    method: "post",
    data: { processTypeList: [1] },
  });
  let shiftSetIdData: any[] = [];
  for (let i = 0; i < intervalDayList.value.length; i++) {
    let newVar = shiftSetMap.value.get(data[0].mesShiftSetId);
    if (newVar == null) {
      ElMessage.error("请重新设置制芯工序默认班制！");
      return;
    }
    let dataNew = {
      shiftSystemId: data[0].mesShiftSetId,
      shiftSystemName: newVar.shiftSystemName,
      planDate:
        searchParam.yearMonthPlan +
        "-" +
        intervalDayList.value[i].date.slice(3, 5),
    };
    shiftSetIdData.push(dataNew);
  }
  return shiftSetIdData;
}
const startData = ref([]);
const displayLines = ref(["a", "b", "c"]);
const oneDayFlag = ref(false);
//点击日期筛选存在数字
async function oneDay(dayDate) {
  loading.value = true;
  if (oneDayFlag.value) {
    dataTableRef.value.setScrollTop(0);
    displayLines.value = ["a", "b", "c"];
    // beforeGetTableList();
    let arr = resolveSearchData(startData.value, displayLines.value.length);
    let intervalId = setInterval(() => {
      if (arr.length > 0) {
        tableData.value = arr;
        loading.value = false;
        clearInterval(intervalId);
      }
    }, 200);
    oneDayFlag.value = false;
  } else {
    oneDayFlag.value = true;
    const targetDateStr = dayDate.date; // 提前计算
    const arr = [];
    startData.value.forEach((item) => {
      item.listPlanActual?.forEach((plan) => {
        if (
          getMonthAndDay(plan.requireDate) === targetDateStr &&
          (plan.planQuantity ?? 0) !== 0
        ) {
          arr.push(item);
        }
      });
    });
    // displayLines.value = ["b"];
    if (arr.length == 0) {
      tableData.value = []
      loading.value = false;
      return;
    }
    let arrNew = resolveSearchData(arr, 3);
    let time = 0;
    let intervalId = setInterval(() => {
      time += 200;
      if (arrNew.length > 0) {
        tableData.value = arrNew;
        loading.value = false;
        clearInterval(intervalId);
      }
      if (arrNew.length == 0 && time > 10000) {
        tableData.value = arrNew;
        loading.value = false;
        clearInterval(intervalId);
      }
    }, 200);
    // loading.value = false;
  }
}
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-table__body td.el-table__cell {
    padding: 0;
    .can_edit_cell:hover {
      color: #409eff !important;
    }
  }
  .el-scrollbar__bar.is-horizontal {
    height: 12px;
    left: 2px;
  }
  .cell {
    padding: 0;
    white-space: pre-wrap;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell > :first-child {
    padding: 3px 12px;
  }

  .el-scrollbar__wrap {
    max-height: calc(100vh - 342px);
    overflow-y: scroll;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}
</style>
